package cn.wjdiankong.levideo.fragment;

import java.util.List;

import com.ss.android.common.applog.GlobalContext;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import cn.wjdiankong.levideo.R;
import cn.wjdiankong.levideo.activity.MainActivity;
import cn.wjdiankong.levideo.activity.SettingActivity;
import cn.wjdiankong.levideo.data.LevideoData;
import cn.wjdiankong.levideo.list.adapter.BaseFragmentListAdapter;
import cn.wjdiankong.levideo.utils.NetworkUtil;
import cn.wjdiankong.levideo.utils.UIUtil;
import cn.wjdiankong.levideo.view.SmileyLoadingView;
import cn.wjdiankong.levideo.view.floatmenu.FloatingActionButton;
import cn.wjdiankong.levideo.view.floatmenu.FloatingActionsMenu;
import cn.wjdiankong.levideo.view.listview.OnDismissCallback;
import cn.wjdiankong.levideo.view.listview.ScaleInAnimationAdapter;
import cn.wjdiankong.levideo.view.listview.SwipeDismissAdapter;

public abstract class BaseFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, OnDismissCallback{

	protected SwipeRefreshLayout swipeLayout;
	protected View loadErrorView;
	protected Button replayBtn;
	protected TextView errorTxt;
	protected View loadNoDataView;
	protected TextView noDataTxt;
	protected BaseFragmentListAdapter adapter;
	protected SmileyLoadingView mSmileyLoadingView;
	protected AbsListView mListView;
	private View footerLoadingView;
	private SmileyLoadingView loadingMoreView;
	public boolean isLocal = false;
	protected String title;
	public int type = 0;

	protected List<LevideoData> videoDataList;

	private boolean isShow = true;
	private FloatingActionButton goTopBtn,goSettingBtn;
	private FloatingActionsMenu floatMenu;

	public void setTitle(String title){
		this.title = title;
	}

	public String getTitle(){
		return title;
	}

	public void goTopRefresh(){
		swipeLayout.setRefreshing(true);
		getBeforeListData();
	}

	public void removeData(LevideoData data){
		if(videoDataList != null && videoDataList.size() > 0){
			videoDataList.remove(data);
			adapter.removeData(data);
		}
		if(adapter.getDataList().size() == 0){
			//删除完了
			showNoDataView();
		}
	}

	public void removeData(int position){
		if(videoDataList != null && videoDataList.size() > 0 && position < videoDataList.size()){
			videoDataList.remove(position);
			adapter.removeData(position);
			if(adapter.getDataList().size() == 0){
				//删除完了
				showNoDataView();
			}
		}
	}

	protected void showErrorView(String msg){
		if(floatMenu != null){
			floatMenu.setVisibility(View.GONE);
		}
		if(loadErrorView != null){
			loadErrorView.setVisibility(View.VISIBLE);
		}
		if(mListView != null){
			mListView.setVisibility(View.GONE);
		}
		if(errorTxt != null){
			errorTxt.setText(msg);
		}
		if(mSmileyLoadingView != null){
			mSmileyLoadingView.stop();
			mSmileyLoadingView.setVisibility(View.GONE);
		}
		if(footerLoadingView != null){
			footerLoadingView.setVisibility(View.GONE);
		}
		if(loadNoDataView != null){
			loadNoDataView.setVisibility(View.GONE);
		}
		if(swipeLayout != null){
			swipeLayout.setVisibility(View.GONE);
		}
	}

	protected void showLoading(){
		if(floatMenu != null){
			floatMenu.setVisibility(View.GONE);
		}
		if(loadErrorView != null){
			loadErrorView.setVisibility(View.GONE);
		}
		if(mListView != null){
			mListView.setVisibility(View.GONE);
		}
		if(mSmileyLoadingView != null){
			mSmileyLoadingView.start();
			mSmileyLoadingView.setVisibility(View.VISIBLE);
		}
		if(footerLoadingView != null){
			footerLoadingView.setVisibility(View.GONE);
		}
		if(loadNoDataView != null){
			loadNoDataView.setVisibility(View.GONE);
		}
		if(swipeLayout != null){
			swipeLayout.setVisibility(View.GONE);
		}
	}

	protected void showDataView(){
		if(floatMenu != null && !isLocal){
			floatMenu.setVisibility(View.VISIBLE);
		}
		if(loadErrorView != null){
			loadErrorView.setVisibility(View.GONE);
		}
		if(mListView != null){
			mListView.setVisibility(View.VISIBLE);
		}
		if(mSmileyLoadingView != null){
			mSmileyLoadingView.stop();
			mSmileyLoadingView.setVisibility(View.GONE);
		}
		if(footerLoadingView != null){
			footerLoadingView.setVisibility(View.GONE);
		}
		if(loadNoDataView != null){
			loadNoDataView.setVisibility(View.GONE);
		}
		if(swipeLayout != null){
			swipeLayout.setVisibility(View.VISIBLE);
		}
	}

	protected void showNoDataView(){
		if(floatMenu != null){
			floatMenu.setVisibility(View.GONE);
		}
		if(loadErrorView != null){
			loadErrorView.setVisibility(View.GONE);
		}
		if(mListView != null){
			mListView.setVisibility(View.GONE);
		}
		if(mSmileyLoadingView != null){
			mSmileyLoadingView.stop();
			mSmileyLoadingView.setVisibility(View.GONE);
		}
		if(footerLoadingView != null){
			footerLoadingView.setVisibility(View.GONE);
		}
		if(loadNoDataView != null){
			loadNoDataView.setVisibility(View.VISIBLE);
		}
		if(noDataTxt != null && isLocal){
			noDataTxt.setText("内容已经删除殆尽");
		}
		if(swipeLayout != null){
			swipeLayout.setVisibility(View.GONE);
		}
	}

	protected void showLoadingMore(){
		if(footerLoadingView != null){
			footerLoadingView.setVisibility(View.VISIBLE);
		}
		if(loadingMoreView != null){
			loadingMoreView.start();
			loadingMoreView.setVisibility(View.VISIBLE);
		}
	}

	protected void hideLoadingMore(){
		if(footerLoadingView != null){
			footerLoadingView.setVisibility(View.GONE);
		}
		if(loadingMoreView != null){
			loadingMoreView.stop();
			loadingMoreView.setVisibility(View.GONE);
		}
	}

	@Override
	public void onRefresh() {
		if(!isLocal){
			swipeLayout.setRefreshing(true);
			getBeforeListData();
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@SuppressLint({ "InlinedApi", "InflateParams", "NewApi" })
	@SuppressWarnings("deprecation")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View layout = LayoutInflater.from(GlobalContext.getContext()).inflate(getLayoutId(), null);
		initFloatMenu(layout);
		mSmileyLoadingView = (SmileyLoadingView) layout.findViewById(R.id.loading_view);
		loadingMoreView = (SmileyLoadingView) layout.findViewById(R.id.loading_more_view);
		loadNoDataView = layout.findViewById(R.id.nodata_layout);
		noDataTxt = (TextView) layout.findViewById(R.id.nodata_txt);
		loadErrorView = layout.findViewById(R.id.error_layout);
		replayBtn = (Button)layout.findViewById(R.id.replay_btn);
		replayBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showLoading();
				getBeforeListData();
			}
		});
		errorTxt = (TextView) layout.findViewById(R.id.error_txt);
		mSmileyLoadingView.setVisibility(View.GONE);
		loadingMoreView.setVisibility(View.GONE);
		swipeLayout = (SwipeRefreshLayout) layout.findViewById(R.id.swipe_refresh);
		swipeLayout.setOnRefreshListener(this);
		swipeLayout.setColorScheme(R.color.cm_color_point_loading_green);
		footerLoadingView = layout.findViewById(R.id.footer_loading);
		swipeLayout.setEnabled(!isLocal);
		return layout;
	}
	
	private void initFloatMenu(View view){
		floatMenu = (FloatingActionsMenu)view.findViewById(R.id.flat_menu);
		goTopBtn = (FloatingActionButton)view.findViewById(R.id.go_top);
		goTopBtn.setColorNormal(0xFF21C777);
		goTopBtn.setColorPressed(0xFF21C777);
		goTopBtn.setIcon(R.drawable.fab_back_top);
		goSettingBtn = (FloatingActionButton)view.findViewById(R.id.go_setting);
		goSettingBtn.setColorNormal(0xFF21C777);
		goSettingBtn.setColorPressed(0xFF21C777);
		goSettingBtn.setIcon(R.drawable.fab_bg_setup);
		goTopBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				goTopRefresh();
				floatMenu.postDelayed(new Runnable(){
					@Override
					public void run() {
						floatMenu.collapse();
					}
				}, 100);
			}
		});
		goSettingBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SettingActivity.startDefaultResult(getActivity(), MainActivity.CODE_SETTING_SORT_TAB);
				floatMenu.postDelayed(new Runnable(){
					@Override
					public void run() {
						floatMenu.collapse();
					}
				}, 100);
			}
		});
		if(isLocal){
			floatMenu.setVisibility(View.GONE);
		}
	}

	protected BaseAdapter getAnimAdapter(AbsListView listView,BaseAdapter adapter){
		ScaleInAnimationAdapter scaleInAnimationAdapter = new ScaleInAnimationAdapter(new SwipeDismissAdapter(adapter, this));
		scaleInAnimationAdapter.setInitialDelayMillis(300);
		scaleInAnimationAdapter.setAbsListView(listView);
		return scaleInAnimationAdapter;
	}


	@Override
	public void onDismiss(AbsListView listView, int[] reverseSortedPositions) {
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
	}

	@SuppressLint("InflateParams")
	protected void initListViewListener(){
		if(mListView == null){
			return;
		}
		mListView.setAdapter(getAnimAdapter(mListView, adapter));
		mListView.setOnScrollListener(new OnScrollListener() {
			int lastposition = 0; // 上一次在屏幕里可见的第一个item在整个listview的位置
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
				View firstView = view.getChildAt(firstVisibleItem);
				if (firstVisibleItem == 0 && (firstView == null || firstView.getTop() == 0)) {
					startLiveViewEnterAnim();
				}
				if (firstVisibleItem > 0) {
					// 即向上滑动列表
					if (firstVisibleItem > lastposition) {
						startLiveViewQuitAnim();
					}
					// 即向下滑动列表
					if (firstVisibleItem < lastposition) {
						startLiveViewEnterAnim();
					}
				}
				lastposition = firstVisibleItem;

			}

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {  
					if (view.getLastVisiblePosition() == view.getCount() - 1) {  
						//加载更多
						if(!isLocal){
							showLoadingMore();
							getAfterListData();
						}
					}  
				}  
			}
		});
	}
	
	private void startLiveViewQuitAnim(){
    	if(!isShow){
    		return;
    	}
    	if(floatMenu == null){
    		return;
    	}
    	isShow = false;
    	floatMenu.collapse();
		int viewHeight = floatMenu.getHeight();
		ObjectAnimator animator = ObjectAnimator.ofFloat(floatMenu, "translationY",  0, viewHeight);
        animator.setDuration(300);
   	    animator.start();
    }
    
    private void startLiveViewEnterAnim(){
    	if(isShow){
    		return;
    	}
    	if(floatMenu == null){
    		return;
    	}
    	isShow = true;
    	int viewHeight = floatMenu.getHeight();
		ObjectAnimator animator = ObjectAnimator.ofFloat(floatMenu, "translationY", viewHeight, 0);
        animator.setDuration(300);
   	    animator.start();
    }

	//下拉数据成功
	protected void loadDownDataFinish(final List<LevideoData> dataList){
		mListView.post(new Runnable() {
			@Override
			public void run() {
				if(dataList == null || dataList.size() == 0){
					if(adapter.isNoData()){
						showNoDataView();
						return;
					}
					UIUtil.showShortHintToast(getActivity(), "暂无最新数据");
					return;
				}
				if(!adapter.isNoData()){
					//原来有数据，就停止上拉数据
					swipeLayout.setRefreshing(false);
				}
				adapter.setBeforeDataList(dataList);
				showDataView();
			}
		});
	}

	//上拉数据成功
	protected void loadUpDataFinish(final List<LevideoData> dataList){
		mListView.post(new Runnable() {
			@Override
			public void run() {
				hideLoadingMore();
				if(dataList == null || dataList.size() == 0){
					if(adapter.isNoData()){
						showNoDataView();
						return;
					}
					UIUtil.showShortHintToast(getActivity(), "数据加载完成");
					return;
				}
				adapter.setAfterDataList(dataList);
			}
		});
	}

	protected void loadDataFailed(){
		mListView.post(new Runnable() {
			@Override
			public void run() {
				swipeLayout.setRefreshing(false);
				hideLoadingMore();
				if(adapter.isNoData()){
					if(!NetworkUtil.isNetworkAvailable(getContext())){
						UIUtil.showShortHintToast(getActivity(), "网络错误，检查网络后重试！");
						showErrorView("网络错误，检查网络后重试！");
						return;
					}
					showErrorView("加载数据失败");
				}else{
					if(!NetworkUtil.isNetworkAvailable(getContext())){
						UIUtil.showShortHintToast(getActivity(), "网络错误，检查网络后重试！");
						return;
					}
					UIUtil.showShortHintToast(getActivity(), "加载数据失败");
				}
			}
		});
	}

	public void setVideoData(List<LevideoData> dataList){
		showDataView();
		videoDataList = dataList;
	}

	protected abstract int getLayoutId();
	protected abstract void getBeforeListData();
	protected abstract void getAfterListData();

}
